var $table;  
var sysInfoField = dataObject.sysInfoField;
var selectionIds = [];  //保存选中ids 
var selectionList = [];//保存多选的对象
var singleStatus = true; //素材选择页面单多选状态
var toolbar = "";
var isSelected = null;
var resourceId = null;
$(function () {
	  var columns =[
					{field: 'state', checkbox: true},
					{field: 'infoTitle' , title: sysInfoField.infoTitle, sortName:'INFO_TITLE' , sortable: true,halign: 'center',align: 'center'},
					{field: 'infoContent' , hide: true, title: sysInfoField.infoContent,formatter: 'infoContentFormatter', sortName:'INFO_CONTENT' , sortable: true,halign: 'center',align: 'left'},
					{field: 'infoType' , title: sysInfoField.infoType,formatter: 'infoTypeFormatter', sortName:'INFO_TYPE' , sortable: true,halign: 'center',align: 'center'},
					{field: 'infoStatus' , title: sysInfoField.infoStatus, formatter: 'infoStatusFormatter', sortName:'INFOSTATUS' , sortable: true,halign: 'center',align: 'center'},
					{field: 'creator.username' , title: sysInfoField.createBy, sortName:'CREATE_BY' , sortable: true,halign: 'center',align: 'center'},
					{field: 'createTime' , title: sysInfoField.createTime, sortName:'CREATE_TIME' , sortable: true,halign: 'center',align: 'center'},
			    	{field: 'action', title: pageData.action, formatter: 'actionFormatter', events: 'actionEvents', clickToSelect: false, width: 150, halign: 'center', align: 'center'}
		         ];
    $table = new BSTable("table",'sys/sysinfo/list', columns,"toolbar",560,'id','ID','sysinfo');
    var queryParams = function(params) {            
         return {
         	  page: params.pageNumber,
         	  limit: params.pageSize,
         	  sidx: params.sortName,
              order: params.sortOrder,
              infoType: vm.search.infoType,
              infoStatus: vm.search.infoStatus ,
              searchBeginTime:$("#searchBeginTime").val(),
              searchEndTime:$("#searchEndTime").val()
              
              //查询字段
             };
     };
	$table.setQueryParams(queryParams);
    $table.init();
    var lang = 'en';
    if(i18nLanguage == 'zh-CN'){
    	lang = 'cn';
    }
	var searchBeginTime = laydate.render({
		   elem: '#searchBeginTime',
		   type: 'datetime',
		   lang: lang,
		   min:'1900-01-01 00:00:00',
	 	   max:'2099-12-31 00:00:00',
		   btns: ['clear', 'confirm'],
		   done: function(value, date){
			   if(value != ''){
				   date.month = date.month - 1;
				   searchEndTime.config.min = date;
			   }else{
				   searchEndTime.config.min = searchBeginTime.config.min;
			   }
		   }
	});

	var searchEndTime = laydate.render({
		   elem: '#searchEndTime',
		   type: 'datetime',
		   lang: lang,
		   min:'1900-01-01 00:00:00',
	 	   max:'2099-12-31 00:00:00',
		   btns: ['clear', 'confirm'],
		   done: function(value, date){
			   if(value != ''){
				   date.month = date.month - 1;
				   searchBeginTime.config.max = date;
			   }else{
				   searchBeginTime.config.max = searchEndTime.config.max;
			   }
		   }
	});
	
});


var vm = new Vue({
	el:'#app',
	data:{
		showList: true,
		title: null,
		sysInfo: {
			infoType:0
		},
		busCompanyList:[],
		search:{
			id:null,
			infoStatus:'',
			infoType:''
		}
	},
	methods: {
		query: function () {
			//vm.reload();
			defaultActions.query();
		},
		add: function(){
		    vm.sysInfo={
		    		busCompanyIdList:[],
		    		infoType:0
		    };
		    vm.busCompanyList = [];
			defaultActions.add(vm);
		},
		update: function (event, id,type) {
		    vm.sysInfo={
		    		infoType:0
		    };
		    if(type == "detail"){
		    	defaultActions.update(id, $("#table"), $path+"sys/sysinfo/info/", vm, function(r){
		        	vm["sysInfo"] = r["sysInfo"];
	                Vue.set(vm.sysInfo,"busCompanyIdList",r.sysInfo.busCompanyIdList);
	                vm.busCompanyList = r.sysInfo.busCompanyList;

		        });
		    }else{
		    	defaultActions.isTheOwenr(id,$("#table"),vm);
		    }
		   
		},
		
		saveOrUpdate: function (event) {
			var isHas = checkCheckBox();
		    $('#defaultForm').bootstrapValidator('validate');
			if($('#defaultForm').data('bootstrapValidator').isValid()&&isHas){
				 var url = vm.sysInfo.id == null || vm.sysInfo.id == ''?  $path+"sys/sysinfo/save" : $path+"sys/sysinfo/update";
				 defaultActions.saveOrUpdate(url ,vm, $("#defaultForm"),"sysInfo",event);
			}
		},
		del: function (event, id) {
			var ids = [];
			if(id==null){
				if(getSelectRows($("#table")) == null){
					return;
				}
				ids = getSelectRows($("#table"));
			}else{
				ids.push(id);
			}
			confirm(pageData.sureDelete, function(){
				$.ajax({
					type: "POST",
				    url:  $path+"sys/sysinfo/delete",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							    alert(pageData.actionSuccess, function(index){
							    	$("#table").bootstrapTable('refresh');
							    	//获取未读消息数目
									changeInfo($path+"sys/sysinfo/infoCount");
								    defaultActions.reload($("#table"),$("#defaultForm"),vm,"sysInfo"); 
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
			
		   // defaultActions.del(id, "../sys/sysinfo/delete", $("#table") ) ;
		},
		audit:function(status){
			defaultActions.audit(status , $path + "sys/sysinfo/audit?status="+status, vm);
		},
		reload: function (event) {
			//获取未读消息数目
			changeInfo($path+"sys/sysinfo/infoCount");
		    defaultActions.reload($("#table"),$("#defaultForm"),vm,"sysInfo"); 
		},
		detail: function (event, id) {
			defaultActions.detail(vm, id, event,"detail");
		},
		assiotCompany:function(index){
			   singleStatus = (index==0)?true:false;
			   selectionIds=[];
			   $.each(vm.sysInfo.busCompanyIdList , function(i , data){
				   selectionIds.push(parseInt(data)); 
			   });
			   selectionList = vm.busCompanyList || [];
			   defaultActions.assiot(sysInfoField.company,'../dialog/company_dialog.html',function(dialogRef) {
				   var objCheck = document.getElementById("checkBox");
				   if(selectionIds!=null &&selectionIds!=""){
					   objCheck.innerHTML="";
				   }
    				$("input[name='busCompany']").val("").change();
    				vm.busCompanyList=[];
    				vm.sysInfo.busCompanyIdList=[];
    				console.info(selectionList);
    				console.info(selectionIds);
    				vm.sysInfo.busCompanyIdList = selectionIds;
					vm.busCompanyList = selectionList;
    				dialogRef.close();
             } );
		}
	}
});
/*操作按钮start*/
function actionFormatter(value, row, index) {
	return [
	        '<a class="detail ml10" href="javascript:void(0)"  data-toggle="tooltip" title="detail"><i class="glyphicon glyphicon-book"></i></a>&nbsp;&nbsp;'
	        ].join('');
}
//校验是否选择运营商
function checkCheckBox(){
	var objCheck = document.getElementById("checkBox");
	console.log(vm.sysInfo.infoType);
	if(vm.sysInfo.infoType==1){
		if(vm.sysInfo.busCompanyIdList==null || vm.sysInfo.busCompanyIdList==""){
			objCheck.innerHTML="<small class='help-block' data-bv-validator='notEmpty' data-bv-for='infoContent' data-bv-result='INVALID' style='color:#a94442'>"+sysInfoField.company+pageData.notEmpty + '！'+"</small>";
			return false;
		}else{
			objCheck.innerHTML="";
		}
	}
	return true;
	
	
}



function infoContentFormatter(value,row){row.infoContent;
	return "<span>"+row.infoContent+"</span>";
}


//校验同步文件是否被过时
function check(value){
	$.ajax({
		type: "POST",
	    url: $path+"sys/sysinfo/checkNet",
	    data: value,
	    success: function(r){
	    	if(r.isCon==0){
	    		location.href=value;
	    	}else if(r.isCon==1){
	    		alert("文件过时已被删除");
	    	}else if(r.isCon==2){
	    		alert("网络不通");
	    	}
	    	
		}
	});
	
}




//0为系统消息，1为用户消息
function infoTypeFormatter(value,row){
	return row.infoType == 0 ? "<span class='label label-success'>"+baseData.MSGTYPE[0].value+"</span>" : 
		 "<span class='label label-success'>"+baseData.MSGTYPE[1].value+"</span>";
}



//0为系统消息，1为用户消息
function infoStatusFormatter(value,row){
	return row.infoStatus == 0 ? "<span class='label label-warning'>"+baseData.INFOSTATUS[0].value+"</span>" : 
		 "<span class='label label-success'>"+baseData.INFOSTATUS[1].value+"</span>";
}

/*表单校验 start*/
$('#defaultForm').bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
	    	    				
	    	infoContent: {
	            message: 'The '+sysInfoField.infoContent+' is not valid',
	            validators: {
	                notEmpty: {
	                    message: sysInfoField.infoContent+pageData.notEmpty + '！'
	                },
	                stringLength: {
	                    min: 1,
	                    max: 50,
	                    message:sysInfoField.infoContent+ pageData.overLength + '50'
	                }
	            }
	        },
	    	    				
	    	infoTitle: {
	            message: 'The '+sysInfoField.infoTitle+' is not valid',
	            validators: {
	                notEmpty: {
	                    message: sysInfoField.infoTitle+pageData.notEmpty + '！'
	                },
	                stringLength: {
	                    min: 1,
	                    max: 25,
	                    message: sysInfoField.infoTitle+pageData.overLength + '25'
	                }
	            }
	        },
	    	infoType: {
	            message: 'The '+sysInfoField.infoType+' is not valid',
	            validators: {
	                notEmpty: {
	                    message: sysInfoField.infoType+pageData.notEmpty + '！'
	                },
	                stringLength: {
	                    min: 1,
	                    max: 20,
	                    message: sysInfoField.infoType+pageData.overLength + '20'
	                }
	            }
	        }
	    	    		    
    }
});
/*表单校验 end*/
